import * as mockApi from '@/services/mockApi'
import { material, project } from '@alilc/lowcode-engine';
import { filterPackages } from '@alilc/lowcode-plugin-inject'
import { IPublicEnumTransformStage } from '@alilc/lowcode-types';
import { getLowcodeModuleById } from '@/services/mockApi'

export const saveSchema = async (id: number) => {
  const schema = project.exportSchema(IPublicEnumTransformStage.Save);
  const packages = await filterPackages(material.getAssets().packages);
  await mockApi.updateLowcodeModuleScheam({ id, schema: JSON.stringify(schema), packages: JSON.stringify(packages) })
}

export const getModuleData = async (id: number) => {
  const res = await getLowcodeModuleById(id);
  const schema = res.data[0]?.schema;
  const packages = res.data[0]?.packages;
  const assets = res.data[0]?.assets;
  return {
    id,
    schema: schema ? JSON.parse(schema) : null,
    packages: packages ? JSON.parse(packages) : null,
    assets
  }
}

export const getPageSchema = async (id: number) => {
  const res = await getLowcodeModuleById(id);
  const schema = res.data[0]?.schema || '{}';
  return JSON.parse(schema)?.componentsTree?.[0] || null
}